<template>
  <!--  jiera-->
  <div class='task_detail'>
    <div class='left'>
      <div class='bg-white content'>
        <PeopleInfo :data='publisher' @refresh='handleRefresh'>
          <div class='time'>{{ dayjs(taskInfo.createdTime).format('YYYY-MM-DD HH:MM:ss') }}</div>
        </PeopleInfo>
        <div class='task_content mt-5'>
          <div class='title'><h1 style='font-size: 1.9em;font-weight: bold;'>{{ taskInfo.title }}</h1></div>
          <div v-if='taskInfo.type!== 0' style='background: #F8F8F8;height:50px;'>
            <div style='display: flex; justify-content: space-between; align-items: center;margin-top: 8px;'>
              <div
                class='bounty'
                style='font-size: 21px;
                margin-top: 10px'
                v-if='taskInfo.type === 1'
              >赏金金额：
                <div style='font-weight: bold;display: inline-block;'>{{ taskInfo.bounty }}</div>
              </div>
              <div class='bountyNum' style='font-size: 21px;margin-top: 10px' v-if='taskInfo.type === 1'
              >赏金数量：
                <div style='font-weight: bold;display: inline-block;'>{{ taskInfo.bountyNum }}</div>
              </div>
              <div
                class='bounty'
                style='font-size: 21px;
                margin-top: 10px'
                v-if='taskInfo.type === 2'
              >求助金额：
                <div style='font-weight: bold;display: inline-block;'>{{ taskInfo.helpBounty }}</div>
              </div>
              <div class='bountyNum' style='font-size: 21px;margin-top: 10px' v-if='taskInfo.type === 2'>求助数量：
                <div style='font-weight: bold;display: inline-block;'>{{ taskInfo.helpBountyNum }}</div>
              </div>
              <div
                class='bounty'
                style='font-size: 21px;
                margin-top: 10px'
                v-if='taskInfo.type === 10'
              >征召金额：
                <div style='font-weight: bold;display: inline-block;'>{{ taskInfo.bounty }}</div>
              </div>
              <div class='bountyNum' style='font-size: 21px;margin-top: 10px' v-if='taskInfo.type === 10'>征召数量：
                <div style='font-weight: bold;display: inline-block;'>{{ taskInfo.bountyNum }}</div>
              </div>
              <div class='distance' style='font-size: 21px;margin-top: 10px'>距离：
                <div style='font-weight: bold;display: inline-block;'>{{ taskInfo.distance }}</div>
              </div>
              <div class='endTime' style='font-size: 21px;margin-top: 10px'>截止时间：
                <div style='font-weight: bold;display: inline-block;'>
                  {{ taskInfo.endTime === 0 ? '' : dayjs(taskInfo.endTime).format('YYYY-MM-DD HH:MM:ss') }}
                </div>
              </div>
            </div>
          </div>
          <div v-if='taskInfo.type === 0'>
            {{ taskInfo.description }}
          </div>
          <Markdown v-model='taskInfo.content' :is-preview='true' style='margin-left: -19px'></Markdown>
        </div>
        <div class='task_info mt-4 flex justify-between items-center gap-8'>
          <div class='flex items-stretch gap-5 cursor-pointer text-sm'>
            <div
              class='flex gap-1'
              hover:text-gray-400
              v-for='handle in handleList'
              :key='handle.icon'
              @click='handleClick(handle.type, taskId)'
            >
              <div
                v-if='taskInfo[handle.checkedFieldName!]'
                :class='handle.checkedIcon'
                :style="{ color: '#409eff' }"
              ></div>
              <div v-else :class='handle.icon'></div>
              <div>{{ taskInfo[handle.fieldName] || 0 }}</div>
            </div>
            <div>总浏览量：{{ taskInfo.allVisitsNum || 0 }}</div>
            <div>粉丝浏览量：{{ taskInfo.fansVisitsNum || 0 }}</div>
            <div>累计发布赏金：{{ taskInfo.redisBountyNum || 0 }}</div>
            <el-button type='primary' size='small' @click.stop='handleTaskData(taskId,taskInfo.type)'>操作日志
            </el-button>
            &nbsp;<el-button type='primary' size='small' @click.stop='handleTaskUpdate(taskId,taskInfo.type)'
                             v-if='taskInfo.userId==currentLoginUserId'>编辑
          </el-button>
            <el-button type='warning' size='small' @click.stop='handleDeleteTask(taskId)'
                       v-if='taskInfo.userId==currentLoginUserId'>删除
            </el-button>
          </div>

        </div>
      </div>
      <!--      任务帖子评论模块-->
      <div class='bg-white comment'>
        <el-tabs v-model='activeTab'>
          <el-tab-pane v-for='item in tabList' :label='item.name' :key='item.name' :name='item.id'>
            <template v-if='activeTab === 0'>
              <Comment :data='commentData' :pagination='pagination' :taskId='taskId' :commentType='0'
                       :receiverList='taskInfo.taskReceiveList'
                       @refresh='handleCommentRefresh(0)'></Comment>
            </template>
            <!--      完成情况-->
            <template v-else>
              <Comment :data='commentData' :pagination='pagination' :taskId='taskId' :commentType='1'
                       :receiverList='taskInfo.taskReceiveList'
                       @refresh='handleCommentRefresh(1)'></Comment>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class='right'>
      <div class='hot_topic'>
        <!--        <HotTopic></HotTopic>-->
        <div class='bg-white rounded'>
          <div class='w-full h-10 bg-gradient-to-r from-[#c0e3ff] to-blue-200 leading-10'
          >&nbsp;&nbsp;任务领取记录
          </div>
          <div style='height:593px'>
            <div class='task_status' style='display: inline-block;margin-left: 10px; text-align: left'
                 v-for='item in taskInfo.taskReceiveList' :key='item.receiverId'>
              <div class='recipien' v-if='item.status !== 0 && item.status !== undefined'>
                领取人：{{ item.receiverName }}
              </div>
              <div class='time' v-if='item.status !== 0 && item.status !== undefined'>
                领取时间：{{ item.receiveTime && dayjs(item.receiveTime).format('YYYY-MM-DD HH:MM:ss') }}
              </div>
              <div class='taskStatus'>
                任务状态：<span v-if='item.status === 0'>任务已取消</span>
                <span v-else-if='item.status === 1'>任务进行中</span>
                <span v-else-if='item.status === 2'>任务已完成</span>
                <span v-else-if='item.status === 3'>任务已结束</span>
                <span v-else>未知状态</span>
              </div>
              <div style='display: flex;'>
                <div class='finish mr-3' v-if='item.finishBut === 0'>
                  <ElButton type='primary'
                            @click='handleChangeTaskStatus(2,item.receiverId !== undefined ? item.receiverId : 0, taskInfo.type)'>
                    完成任务
                  </ElButton>
                </div>
                <div class='collect mr-3' v-if='item.receiveBut === 0'>
                  <ElButton type='primary'
                            @click='handleChangeTaskStatus(1,item?.receiverId !== undefined && item?.receiverId !== null ? item.receiverId : 0, taskInfo.type)'>
                    领取任务
                  </ElButton>
                </div>
                <div class='collect mr-3' v-if='item.cancelBut === 0'>
                  <ElButton type='primary'
                            @click='handleChangeTaskStatus(0,item.receiverId !== undefined ? item.receiverId : 0, taskInfo.type)'>
                    取消任务
                  </ElButton>
                </div>
              </div>
              <div class='divider' style='width: 370px'></div>
            </div>
          </div>
        </div>
      </div>
      <div class='advertisement'></div>
    </div>
  </div>
</template>

<script lang='ts' setup>
import {ref, onMounted, watch} from 'vue'
import {ElButton, ElMessage, ElMessageBox} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'
import dayjs from 'dayjs'
import Markdown from '@/components/Markdown.vue'
import HotTopic from '@/components/HotTopic.vue'
import Comment from '@/components/Comment.vue'
import {useUserStore} from '@/stores/user'
import {useWsLoginStore} from '@/stores/ws'

const route = useRoute()
const userStore = useUserStore()
const taskId = computed(() => {
  return route.params.id as string
})
const $emit = defineEmits(['refresh'])
// 存储是否显示全屏大图的状态
const isFullSizeImageVisible = ref(false)
// 存储当前要展示的全屏大图的源地址
const fullSizeImageSrc = ref('')
// 存储当前图片在图片列表中的索引
const currentIndex = ref(0)
const loginStore = useWsLoginStore()

const taskInfo = ref<any>({})
const currentLoginUserId = computed(() => userStore.userInfo.uid || '100000')
const getTaskInfo = async (id: string) => {
  const result = await service.task.findById(id)
  taskInfo.value = result.data
}

const showFullSizeImage = (image) => {
  isFullSizeImageVisible.value = true
  fullSizeImageSrc.value = image
  currentIndex.value = taskInfo.images.indexOf(image)
}

const hideFullSizeImage = () => {
  isFullSizeImageVisible.value = false
}

const prevImage = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
    fullSizeImageSrc.value = taskInfo.images[currentIndex.value]
  }
}

const nextImage = () => {
  if (currentIndex.value < taskInfo.images.length - 1) {
    currentIndex.value++
    fullSizeImageSrc.value = taskInfo.images[currentIndex.value]
  }
}


const commentList = ref([])
const commentTotal = ref(0)
const pagination = ref({
  pageSize: 10,
  pageNum: 1,
  total: 0,
})

const commentData = computed(() => ({
  list: commentList.value,
  total: commentTotal.value,
}))
const getComments = async (type: number) => {
  const queryData = {
    taskId: taskId.value,
    pageSize: pagination.value.pageSize,
    pageNum: pagination.value.pageNum,
    type: type,
  }
  const result = await service.comment.list(queryData)
  commentList.value = result.list
  commentTotal.value = result.total
}

const publisher = computed(() => ({
  avatar: taskInfo.value.userAvatar,
  name: taskInfo.value.createdName,
  isFollow: taskInfo.value.isFollow,
  id: taskInfo.value.userId,
}))

const handleRefresh = () => {
  getTaskInfo(taskId.value)
}
const activeTab = ref(0)

// 监听标签切换
watch(activeTab, async (newVal) => {
  // 没登录先登录
  if (!userStore.isSign) {
    loginStore.showLogin = true
    return
  }
  // 只有自己tab传userId
  getComments(newVal)
})


const handleCommentRefresh = (type: number) => {
  getComments(type)
}

onMounted(async () => {
  getTaskInfo(taskId.value)
  getComments(0)
})

// 点击任务按钮
const handleChangeTaskStatus = async (type: number, receiverId: string | number, taskType: number) => {
  // 求助贴需要支付完成后才可领取任务
  if (type === 1 && taskType === 2) {
    await service.task.updateTaskStatus({type, taskId: taskId.value, receiverId}).then((res) => {
      alert('支付账号：sfkxue7105@sandbox.com；登录密码：111111；支付密码：111111' +
        '如果客户端登录失败请下载手机版扫码支付')
      const alipayHtml = res.data
      localStorage.setItem('alipayHtml', '')
      localStorage.setItem('alipayHtml', alipayHtml)
      router.push('/main/pay')
      getTaskInfo(taskId.value)
    }).catch((err) => {
      ElMessage({
        message: '任务还未激活',
        type: 'warning',
      })
    })
  } else {
    await service.task.updateTaskStatus({type, taskId: taskId.value, receiverId}).then((res) => {
      getTaskInfo(taskId.value)
    }).catch((err) => {
      ElMessage({
        message: '任务还未激活',
        type: 'warning',
      })
    })
  }
}


const tabList = [
  {
    name: '评论',
    id: 0,
  },
  {
    name: '完成情况',
    id: 1,
  },
]


const handleList = ref([
  {
    icon: 'i-carbon-thumbs-up',
    checkedIcon: 'i-carbon-thumbs-up-filled',
    type: 'liked',
    fieldName: 'likedNum',
    checkedFieldName: 'isLiked',
  },
  {
    icon: 'i-carbon-star',
    checkedIcon: 'i-carbon-star-filled',
    type: 'collected',
    fieldName: 'collectedNum',
    checkedFieldName: 'isCollected',
  },
])

const handleClick = async (type: string, id: string | number) => {
  if (type === 'liked') {
    await service.task.likeTask(id)
    getTaskInfo(taskId.value)
  } else if (type === 'collected') {
    await service.task.collectTask(id)
    getTaskInfo(taskId.value)
  }
}


const taskPagination = ref<any>({
  pageSize: 10,
  pageNum: 1,
  total: 0,
})

const getTaskList = async (params?: object) => {
  const queryData = {
    ...params,
    pageSize: taskPagination.value.pageSize,
    pageNum: taskPagination.value.pageNum,
  }
  const data = (await service.task.list(queryData)) || {}
  handleList.value = data.list
  taskPagination.value.total = data.total
}
const router = useRouter()

const handleDeleteTask = async (id: any) => {
  const confirmResult = await ElMessageBox.confirm('确认删除该任务?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  if (confirmResult) {
    const data = {taskId: id}
    await service.task.delete(data)
    router.push(`/main/home/`)
    $emit('refresh')
  }
}

const handleTaskUpdate = (id: string, type: number) => {
  router.push({
    path: `/main/task/handle?id=${id}`,
    query: {
      taskType: type,
      id: id,
    },
  })
}

const handleTaskData = (id: string, type: number) => {
  router.push({
    path: `/main/task/search?id=${id}`,
    query: {
      taskType: type,
      id: id,
    },
  })
}


// 监听taskId变化，重新渲染页面数据
watch(taskId, () => {
  getTaskInfo(taskId.value)
})

</script>

<style lang='scss' scoped>
.task_detail {
  display: flex;
  gap: 20px;

  .left {
    width: 70%;
    padding-bottom: 20px;

    .content {
      padding: 20px;
      margin-bottom: 20px;
      border-radius: 5px;

      .task_status {
        display: flex;
        align-items: center;
      }
    }

    .comment {
      padding: 15px 10px;
      border-radius: 5px;
    }
  }

  .right {
    flex: 1;
  }

  .images img {
    width: 40%;
    height: auto;
    cursor: pointer;
  }

  .image-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    alignItems: center;
    z-index: 999;
  }

  .image-modal img {
    max-width: 90%;
    max-height: 90%;
  }

  .image-modal-navigation {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 10px;
  }

  .image-modal-navigation button {
    padding: 5px 10px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    cursor: pointer;
  }


}

.delete-button {
  background: none;
  border: none;
  border-radius: 4px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.fas.fa-trash-alt {
  margin-right: 6px;
  font-size: 16px;
}

.small-text {
  font-size: 1.0em; /* 根据需要调整字体大小，这里设置为比原来小的 0.7 倍 */
}
</style>
